package log

import (
	"io/ioutil"
	"log"
	"os"
	"sync"
)

//logger
var (
	errorLog = log.New(os.Stdout, "\033[31m[error]\033[0m ", log.LstdFlags|log.Lshortfile)
	infoLog  = log.New(os.Stdout, "\033[32m[info] \033[0m ", log.LstdFlags)
	warnLog  = log.New(os.Stdout, "\033[33m[warn] \033[0m ", log.LstdFlags)
	loggers  = []*log.Logger{errorLog, warnLog, infoLog}
	mu       sync.Mutex
)

//log method
var (
	Error  = errorLog.Println
	Errorf = errorLog.Printf
	Warn   = warnLog.Println
	Warnf  = warnLog.Printf
	Info   = infoLog.Print
	Infof  = infoLog.Printf
)

//log level
const (
	InfoLevel = iota
	WarnLevel
	ErrorLevel
)

// SetLevel controls log level
func SetLevel(level int) {
	mu.Lock()
	defer mu.Unlock()

	//default use os.Stdout
	for _, logger := range loggers {
		logger.SetOutput(os.Stdout)
	}

	if ErrorLevel < level {
		errorLog.SetOutput(ioutil.Discard)
		warnLog.SetOutput(ioutil.Discard)
		infoLog.SetOutput(ioutil.Discard)
	} else if WarnLevel < level {
		warnLog.SetOutput(ioutil.Discard)
		infoLog.SetOutput(ioutil.Discard)
	} else if InfoLevel < level {
		infoLog.SetOutput(ioutil.Discard)
	}
}
